package com.atguigu.exercise;

import org.junit.Test;

/**
 * @author : leimingchao
 * @date Date : 2021年10月05日 11:33
 */
public class StringDemo {

    /**
     * 2. 将一个字符串进行反转。将字符串中指定部分进行反转。比如“abcdefg”反转为”abfedcg”
     * 方式一：转换为char[]
     */
    public String reverse(String str,int startIndex,int endIndex) {

        if (str != null) {
            char[] arr = str.toCharArray();

            for (int x = startIndex,y = endIndex; x < y;x++,y--) {
                char temp = arr[x];
                arr[x] = arr[y];
                arr[y] = temp;
            }
            return new String(arr);
        }
        return null;
    }

    /**
     * 方式二：使用String的拼接操作
     */
    public String reverse1(String str,int startIndex,int endIndex) {

        if (str != null) {
            String reverseStr = str.substring(0,startIndex);
            for (int i = endIndex; i >= startIndex;i-- ) {
                reverseStr += str.charAt(i);
            }
            reverseStr += str.substring(endIndex + 1);
            return reverseStr;
        }
        return null;
    }

    /**
     * 方式三：使用StringBuffer/StringBuilder替换String
     */
    public String reverse2(String str,int startIndex,int endIndex) {

        if (str != null) {
            StringBuilder sb = new StringBuilder(str.length());

            sb.append(str.substring(0,startIndex));
            for (int i = endIndex; i >= startIndex;i-- ) {
                sb.append(str.charAt(i));
            }
            sb.append(str.substring(endIndex + 1));
            return sb.toString();
        }
        return null;
    }

    @Test
    public void testReverse() {
        String str = "abcdefg";
        // String reverse = reverse(str, 2, 5);
        // String reverse = reverse1(str, 2, 5);
        String reverse = reverse2(str, 2, 5);
        System.out.println(reverse);
    }
}
